/**
 *  学习目标：Todos 案例
 */
import React from 'react'
import './styles/base.css'
import './styles/index.css'
import { Header } from './components/Header'
import { Main } from './components/Main'
import { Footer } from './components/Footer'
export default class App extends React.Component {
  state = {
    list: [
      { id: 1, content: '游戏', flag: true },
      { id: 2, content: '旅游', flag: false },
      { id: 3, content: '音乐', flag: true },
    ],
    type: 'all'
  }
  render() {
    return (
      <section className='todoapp'>
        {/* 头部 */}
        <Header addList={this.addList}></Header>
        {/* 主体 */}
        <Main list={this.state.list} itemRemove={this.itemRemove} radioCheck={this.radioCheck} allCheck={this.allCheck} type={this.state.type}></Main>
        {/* 底部 */}
        <Footer list={this.state.list} itemFilter={this.itemFilter} type={this.state.type} clearCompleted={this.clearCompleted}></Footer>
      </section>
    )
  }
  itemRemove = (id) => {
    this.setState({
      list: this.state.list.filter(item => item.id !== id)
    })
  }
  radioCheck = (id) => {
    this.setState({
      list: this.state.list.map(item => {
        if (item.id === id) {
          return {
            ...item,
            flag: !item.flag
          }
        } else {
          return item
        }
      })
    })
  }
  allCheck = (flag) => {
    this.setState({
      list: this.state.list.map(item => ({ ...item, flag: flag }))
    })
  }
  addList = (content) => {
    this.setState({
      list: [{ id: Date.now(), content, flag: false }, ...this.state.list]
    })
  }
  itemFilter = (type) => {
    this.setState({
      type
    })
  }
  clearCompleted = () => {
    this.setState({
      list: this.state.list.filter(item => !item.flag)
    })
  }
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.list))
  }
  componentDidMount() {
    this.setState({
      list: JSON.parse(localStorage.getItem('todos') || [])
    })
  }
}
